package repository

import (
	"errors"
	"fmt"
	"github.com/honwee/awm/internal/model"
	"github.com/honwee/awm/pkg/database"
	"gorm.io/gorm"
)

type ProjectUserRepository struct {
	db *gorm.DB
}

func NewProjectUserRepository() *ProjectUserRepository {
	return &ProjectUserRepository{
		db: database.DB,
	}
}

// FindByAPIKey 根据API Key查询项目用户关系
func (r *ProjectUserRepository) FindByAPIKey(apiKey string) (*model.ProjectUser, error) {
	var projectUser model.ProjectUser
	err := r.db.Where("api_key = ?", apiKey).First(&projectUser).Error
	if err != nil {
		return nil, err
	}
	return &projectUser, nil
}

// UpdateAPIKey 更新API Key
func (r *ProjectUserRepository) UpdateAPIKey(projectID uint64, userID string, apiKey string) error {
	return r.db.Model(&model.ProjectUser{}).
		Where("project_id = ? AND user_id = ?", projectID, userID).
		Update("api_key", apiKey).Error
}

// ValidateProjectUser 验证项目用户关系是否存在
func (r *ProjectUserRepository) ValidateProjectUser(projectID uint64, userID string) (bool, error) {
	var count int64
	err := r.db.Model(&model.ProjectUser{}).
		Where("project_id = ? AND user_id = ?", projectID, userID).
		Count(&count).Error
	return count > 0, err
}

// Update 更新项目用户记录
func (r *ProjectUserRepository) Update(projectUser *model.ProjectUser) error {
	result := r.db.Save(projectUser)
	if result.Error != nil {
		return fmt.Errorf("failed to update project user: %w", result.Error)
	}
	return nil
}

// FindByProjectIDAndUserID 根据项目ID和用户ID查找项目用户
func (r *ProjectUserRepository) FindByProjectIDAndUserID(projectID uint64, userID string) (*model.ProjectUser, error) {
	var projectUser model.ProjectUser
	result := r.db.Where("project_id = ? AND user_id = ?", projectID, userID).First(&projectUser)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, fmt.Errorf("failed to find project user: %w", result.Error)
	}
	return &projectUser, nil
}

// CreateProjectUser 创建项目用户关系
func (r *ProjectUserRepository) CreateProjectUser(projectUser *model.ProjectUser) error {
	result := r.db.Create(projectUser)
	if result.Error != nil {
		return fmt.Errorf("failed to create project user: %w", result.Error)
	}
	return nil
}
